<template>
  <div class="home">
    <div class="welcome-section">
      <animated-card>
        <h1>欢迎使用数据 API 管理平台</h1>
        <p>在这里，您可以轻松管理和监控您的 API 和数据库连接。</p>
      </animated-card>
    </div>

    <div class="stats-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <animated-card>
            <template #icon><DatabaseOutlined /></template>
            <div class="stat-item">
              <div class="stat-value">{{ stats.databaseCount }}</div>
              <div class="stat-label">数据库连接</div>
            </div>
          </animated-card>
        </a-col>
        <a-col :span="6">
          <animated-card>
            <template #icon><ApiOutlined /></template>
            <div class="stat-item">
              <div class="stat-value">{{ stats.apiCount }}</div>
              <div class="stat-label">API 接口</div>
            </div>
          </animated-card>
        </a-col>
        <a-col :span="6">
          <animated-card>
            <template #icon><CheckCircleOutlined /></template>
            <div class="stat-item">
              <div class="stat-value">{{ stats.activeApiCount }}</div>
              <div class="stat-label">活跃 API</div>
            </div>
          </animated-card>
        </a-col>
        <a-col :span="6">
          <animated-card>
            <template #icon><BarChartOutlined /></template>
            <div class="stat-item">
              <div class="stat-value">{{ stats.todayApiCalls }}</div>
              <div class="stat-label">今日 API 调用</div>
            </div>
          </animated-card>
        </a-col>
      </a-row>
    </div>

    <statistics class="mt-4" />

    <div class="quick-actions mt-4">
      <a-row :gutter="16">
        <a-col :span="12">
          <animated-card class="action-card">
            <template #title>快捷操作</template>
            <a-row :gutter="[16, 16]">
              <a-col :span="12">
                <a-button type="primary" block @click="navigateTo('/database')">
                  <template #icon><DatabaseOutlined /></template>
                  管理数据库
                </a-button>
              </a-col>
              <a-col :span="12">
                <a-button type="primary" block @click="navigateTo('/api')">
                  <template #icon><ApiOutlined /></template>
                  管理 API
                </a-button>
              </a-col>
              <a-col :span="12">
                <a-button block @click="showCreateApi = true">
                  <template #icon><PlusOutlined /></template>
                  创建 API
                </a-button>
              </a-col>
              <a-col :span="12">
                <a-button block @click="showCreateConnection = true">
                  <template #icon><PlusOutlined /></template>
                  添加连接
                </a-button>
              </a-col>
            </a-row>
          </animated-card>
        </a-col>
        <a-col :span="12">
          <animated-card class="action-card">
            <template #title>最近活动</template>
            <a-list
              :data-source="recentActivities"
              :loading="loading"
              size="small"
            >
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-list-item-meta>
                    <template #avatar>
                      <a-avatar :style="{ backgroundColor: item.color }">
                        {{ item.icon }}
                      </a-avatar>
                    </template>
                    <template #title>
                      {{ item.title }}
                    </template>
                    <template #description>
                      {{ item.time }}
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </template>
            </a-list>
          </animated-card>
        </a-col>
      </a-row>
    </div>

    <form-modal
      v-model:open="showCreateApi"
      title="创建 API"
      :loading="submitting"
      :rules="apiRules"
      @submit="handleCreateApi"
    >
      <a-form-item label="API 名称" name="name">
        <a-input v-model:value="apiForm.name" placeholder="请输入 API 名称" />
      </a-form-item>
      <a-form-item label="请求方法" name="method">
        <a-select v-model:value="apiForm.method" placeholder="请选择请求方法">
          <a-select-option value="GET">GET</a-select-option>
          <a-select-option value="POST">POST</a-select-option>
          <a-select-option value="PUT">PUT</a-select-option>
          <a-select-option value="DELETE">DELETE</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="API 路径" name="path">
        <a-input v-model:value="apiForm.path" placeholder="请输入 API 路径" />
      </a-form-item>
    </form-modal>

    <form-modal
      v-model:open="showCreateConnection"
      title="添加数据库连接"
      :loading="submitting"
      :rules="connectionRules"
      @submit="handleCreateConnection"
    >
      <a-form-item label="连接名称" name="name">
        <a-input v-model:value="connectionForm.name" placeholder="请输入连接名称" />
      </a-form-item>
      <a-form-item label="数据库类型" name="type">
        <a-select v-model:value="connectionForm.type" placeholder="请选择数据库类型">
          <a-select-option value="mysql">MySQL</a-select-option>
          <a-select-option value="postgresql">PostgreSQL</a-select-option>
          <a-select-option value="sqlserver">SQL Server</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="主机地址" name="host">
        <a-input v-model:value="connectionForm.host" placeholder="请输入主机地址" />
      </a-form-item>
      <a-form-item label="端口" name="port">
        <a-input-number v-model:value="connectionForm.port" :min="1" :max="65535" style="width: 100%" />
      </a-form-item>
    </form-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useApiStore } from '../stores/api'
import { useDatabaseStore } from '../stores/database'
import { useAppStore } from '../stores/app'
import {
  DatabaseOutlined,
  ApiOutlined,
  CheckCircleOutlined,
  BarChartOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'
import AnimatedCard from '../components/AnimatedCard.vue'
import FormModal from '../components/FormModal.vue'
import Statistics from '../components/Statistics.vue'

const router = useRouter()
const apiStore = useApiStore()
const databaseStore = useDatabaseStore()
const appStore = useAppStore()

const stats = ref({
  databaseCount: 0,
  apiCount: 0,
  activeApiCount: 0,
  todayApiCalls: 0
})

const loading = ref(false)
const submitting = ref(false)
const showCreateApi = ref(false)
const showCreateConnection = ref(false)

const apiForm = ref({
  name: '',
  method: 'GET',
  path: ''
})

const connectionForm = ref({
  name: '',
  type: 'mysql',
  host: '',
  port: 3306
})

const apiRules = {
  name: [{ required: true, message: '请输入 API 名称' }],
  method: [{ required: true, message: '请选择请求方法' }],
  path: [{ required: true, message: '请输入 API 路径' }]
}

const connectionRules = {
  name: [{ required: true, message: '请输入连接名称' }],
  type: [{ required: true, message: '请选择数据库类型' }],
  host: [{ required: true, message: '请输入主机地址' }],
  port: [{ required: true, message: '请输入端口' }]
}

const recentActivities = ref([
  {
    icon: 'A',
    color: '#1890ff',
    title: '创建了新的 API',
    time: '10 分钟前'
  },
  {
    icon: 'D',
    color: '#52c41a',
    title: '添加了数据库连接',
    time: '30 分钟前'
  },
  {
    icon: 'T',
    color: '#faad14',
    title: '测试了 API 接口',
    time: '1 小时前'
  }
])

const navigateTo = (path) => {
  router.push(path)
}

const handleCreateApi = async (values) => {
  submitting.value = true
  try {
    await apiStore.createAPI(values)
    appStore.success('创建成功')
    showCreateApi.value = false
    await fetchStats()
  } catch (error) {
    appStore.error('创建失败')
  } finally {
    submitting.value = false
  }
}

const handleCreateConnection = async (values) => {
  submitting.value = true
  try {
    await databaseStore.createConnection(values)
    appStore.success('创建成功')
    showCreateConnection.value = false
    await fetchStats()
  } catch (error) {
    appStore.error('创建失败')
  } finally {
    submitting.value = false
  }
}

const fetchStats = async () => {
  try {
    const [apiStats, dbStats] = await Promise.all([
      apiStore.fetchStatistics('day'),
      databaseStore.fetchStatistics()
    ])

    stats.value = {
      databaseCount: dbStats.total,
      apiCount: apiStats.total,
      activeApiCount: apiStats.active,
      todayApiCalls: apiStats.todayCalls
    }
  } catch (error) {
    appStore.addNotification({
      type: 'error',
      message: '获取统计数据失败',
      description: error.message
    })
  }
}

onMounted(() => {
  fetchStats()
})
</script>

<style scoped>
.home {
  padding: 24px;
}

.welcome-section {
  margin-bottom: 24px;
}

.welcome-section h1 {
  font-size: 24px;
  margin-bottom: 8px;
}

.welcome-section p {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-item {
  text-align: center;
  padding: 16px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

.mt-4 {
  margin-top: 16px;
}

.quick-actions {
  margin-bottom: var(--spacing-xl);
}

.action-card {
  height: 100%;
}

/* 暗色主题适配 */
[data-theme='dark'] .welcome-section p {
  color: rgba(255, 255, 255, 0.45);
}

[data-theme='dark'] .stat-label {
  color: rgba(255, 255, 255, 0.45);
}

/* 响应式布局 */
@media (max-width: 768px) {
  .home {
    padding: var(--spacing-md);
  }

  .welcome-section {
    padding: var(--spacing-lg) 0;
  }

  .welcome-section h1 {
    font-size: 24px;
  }

  .stat-value {
    font-size: 24px;
  }
}
</style>